<?php
require_once('db.inc.php');
require_once('type_transaction.class.php');
require_once('type_bien.class.php');
require_once('localisation.class.php');
require_once('photo.class.php');

class annonce {
	var $id;
	var $type_transaction;
	var $type_bien;
	var $localisation;
	var $photos = array();
	var $reference;
	var $adresse;
	var $prix;
	var $surface;
	var $piece;
	var $nb_chambre;
	var $nb_salle_eau;
	var $nb_salle_bain;
	var $num_etage;
	var $nb_etage;
	var $parking;
	var $nb_place_parking;
	var $rdc;
	var $ascenseur;
	var $meuble;
	var $cave;
	var $balcon;
	var $terrasse;
	var $piscine;
	var $anciennete;
	var $etat_bien;
	var $eau_chaude;
	var $chauffage;	
	var $cuisine;
	var $conseil;
	var $description;
	var $created_at;
	var $updated_at;
	var $highlight;
	var $is_display;
	var $already_send;

	function annonce($id=0)
	{
		$this->id = $id;
		$this->type_transaction = new type_transaction();
		$this->type_bien = new type_bien();
		$this->localisation = new localisation();
		if ($this->id != 0) {
    		$rs = sql_query("SELECT * FROM annonce WHERE id=" . $this->id);
    		
            $this->type_transaction  = new type_transaction( $rs->fields['type_transaction_id'] );
            $this->type_bien         = new type_bien($rs->fields['type_bien_id']);
            $this->localisation      = new localisation($rs->fields['localisation_id']);
            $this->photos            = $this->getPhoto();
            $this->reference         = stripslashes($rs->fields['reference']);
            $this->adresse           = stripslashes($rs->fields['adresse']);
            $this->prix              = $rs->fields['prix'];
            $this->surface           = $rs->fields['surface'];
            $this->piece             = $rs->fields['piece'];
            $this->nb_chambre        = $rs->fields['nb_chambre'];
            $this->nb_salle_eau      = $rs->fields['nb_salle_eau'];
            $this->nb_salle_bain     = $rs->fields['nb_salle_bain'];
            $this->num_etage         = $rs->fields['num_etage'];
            $this->nb_etage          = $rs->fields['nb_etage'];
            $this->parking           = $rs->fields['parking'];
            $this->nb_place_parking  = $rs->fields['nb_place_parking'];
            $this->rdc               = $rs->fields['rdc'];
            $this->ascenseur         = $rs->fields['ascenseur'];
            $this->meuble            = $rs->fields['meuble'];
            $this->cave              = $rs->fields['cave'];
            $this->balcon            = $rs->fields['balcon'];
            $this->terrasse          = $rs->fields['terrasse'];
            $this->piscine           = $rs->fields['piscine'];
            $this->anciennete        = stripslashes($rs->fields['anciennete']);
            $this->etat_bien         = $rs->fields['etat_bien'];
            $this->eau_chaude        = $rs->fields['eau_chaude'];
            $this->cuisine           = $rs->fields['cuisine'];
            $this->chauffage         = $rs->fields['chauffage'];
            $this->conseil           = stripslashes($rs->fields['conseil']);
            $this->description       = stripslashes($rs->fields['description']);
            $this->created_at        = $rs->fields['created_at'];
            $this->updated_at        = $rs->fields['updated_at'];
            $this->highlight         = $rs->fields['highlight'];
            $this->is_display        = $rs->fields['is_display'];
            $this->already_send      = $rs->fields['already_send'];
		}
	}

	function reload()
	{
		$this->annonce($this->id);
	}

	function getByReference($ref)
	{
		$rs = sql_query("SELECT id FROM annonce WHERE reference='" . $ref . "'");
		if ($rs->fields['id'] > 0) {
			$this->id = $rs->fields['id'];
			$this->reload();
			return true;
		}
		return false;
	}

	function setAlreadySend($nb=1) {
		$sql = "UPDATE annonce
				SET already_send = '" . $nb . "'
				WHERE id=" . $this->id . " LIMIT 1";
		$recordSet = sql_query($sql);
		if (!$recordSet) {
			log_error("Erreur MySQL dans le marquage de l'état DEJA ENVOYE d'une annonce > sql: " . trim($sql) . " \nError: " . $conn->ErrorMsg());
			return false;
		}
	}

	function save()
	{
		global $conn;
		$flag = '';
		if ($this->id == 0)
		{
		    $sql = "INSERT INTO annonce (
		              type_transaction_id,
		              type_bien_id,
		              localisation_id,
		              reference,
		              adresse,
		              prix,
		              surface,
		              piece,
		              nb_chambre,
		              nb_salle_eau,
		              nb_salle_bain,
		              num_etage,
		              nb_etage,
		              parking,
		              nb_place_parking,
		              rdc,
		              ascenseur,
		              meuble,
		              cave,
		              balcon,
		              terrasse,
		              piscine,
		              anciennete,
		              etat_bien,
		              eau_chaude,
		              cuisine,
		              chauffage,
		              conseil,
		              description,
		              is_display,
		              already_send,
		              created_at,
		              updated_at
		            ) VALUES (
		              '" . $this->type_transaction->id . "',
		              '" . $this->type_bien->id . "',
		              '" . $this->localisation->id . "',
		              '" . addslashes($this->reference) . "',
		              '" . addslashes($this->adresse) . "',
		              '" . $this->prix . "',
		              '" . $this->surface . "',
		              '" . $this->piece . "',
		              '" . $this->nb_chambre . "',
		              '" . $this->nb_salle_eau . "',
		              '" . $this->nb_salle_bain . "',
		              '" . $this->num_etage . "',
		              '" . $this->nb_etage . "',
		              '" . $this->parking . "',
		              '" . $this->nb_place_parking . "',
		              '" . $this->rdc . "',
		              '" . $this->ascenseur . "',
		              '" . $this->meuble . "',
		              '" . $this->cave . "',
		              '" . $this->balcon . "',
		              '" . $this->terrasse . "',
		              '" . $this->piscine . "',
		              '" . addslashes($this->anciennete) . "',
		              '" . $this->etat_bien . "',
		              '" . $this->eau_chaude . "',
		              '" . $this->cuisine . "',
		              '" . $this->chauffage . "',
		              '" . addslashes($this->conseil) . "',
		              '" . addslashes($this->description) . "',
		              '0',
		              '0',
		              NOW(),
		              NOW()
		            )";
		}
		else
		{
			$sql = "UPDATE annonce SET
			          type_transaction_id='" . $this->type_transaction->id . "',
			          type_bien_id='" . $this->type_bien->id . "',
			          localisation_id='" . $this->localisation->id . "',
			          reference='" . addslashes($this->reference) . "',
			          adresse='" . addslashes($this->adresse) . "',
			          prix='" . $this->prix . "',
			          surface='" . $this->surface . "',
			          piece='" . $this->piece . "',
			          nb_chambre='" . $this->nb_chambre . "',
			          nb_salle_eau='" . $this->nb_salle_eau . "',
			          nb_salle_bain='" . $this->nb_salle_bain . "',
			          num_etage='" . $this->num_etage . "',
			          nb_etage='" . $this->nb_etage . "',
			          parking='" . $this->parking . "',
			          nb_place_parking='" . $this->nb_place_parking . "',
			          rdc='" . $this->rdc . "',
			          meuble='" . $this->meuble . "',
			          ascenseur='" . $this->ascenseur . "',
			          cave='" . $this->cave . "',
			          balcon='" . $this->balcon . "',
			          terrasse='" . $this->terrasse . "',
			          piscine='" . $this->piscine . "',
			          anciennete='" . addslashes($this->anciennete) . "',
			          etat_bien='" . $this->etat_bien . "',
			          eau_chaude='" . $this->eau_chaude . "',
			          cuisine='" . $this->cuisine . "',
			          chauffage='" . $this->chauffage . "',
			          conseil='" . addslashes($this->conseil) . "',
			          description='" . addslashes($this->description) . "',
			          highlight='" . $this->highlight . "',
			          is_display='" . $this->is_display . "',
			          updated_at= NOW()
			        WHERE id=" . $this->id . " LIMIT 1";
		}
		if ($conn->Execute($sql) === false) {
			if ($conn->ErrorNo() == 1062)
				return ERROR_1062;
			else {
				log_error("Erreur MySQL inconnue dans la SAUVEGARDE de annonce > sql: " . trim($sql));
				return ERROR_MYSQL;
			}
		}
        $this->id = $conn->Insert_ID();        
        return true;
	}
	
	function delete()
	{
        foreach ($this->photos as $photo) {
            $photo->delete();
        }
		sql_query("DELETE FROM annonce WHERE id=" . $this->id);
	}


    /*
     * Gestion des photos
     */
	function getPhoto()
	{
        $data = array();
        foreach (photo::getPhotoIdsFromAnnonceId($this->id) as $photo_id) {
            $tmp = new photo($photo_id);
            $data[] = new photo($photo_id);
        }
        return $data;
	}

	function addPhoto($photo)
	{
        $photo->annonce_id = $this->id;
        $photo->save();
        $this->reload();
	}

	function deletePhoto($photo)
	{
        $photo->delete();
        $this->reload();
	}

    /*
     * Methodes utiles
     */
	function getAll($order='updated_at')
	{
		$data = array();
		$recordSet = sql_query("SELECT * FROM annonce ORDER BY " . $order . " DESC");
		while (!$recordSet->EOF) {
			$id = $recordSet->fields['id'];
			$data[$id]['type_transaction'] = $this->type_transaction->getLibelle( $recordSet->fields['type_transaction_id'] );
			$data[$id]['type_bien'] = $this->type_bien->getLibelle( $recordSet->fields['type_bien_id'] );
			$data[$id]['localisation'] = $this->localisation->getLibelle( $recordSet->fields['localisation_id'] );
			$data[$id]['reference'] = $recordSet->fields['reference'];
			$data[$id]['prix'] = $recordSet->fields['prix'];
			$data[$id]['is_display'] = $recordSet->fields['is_display'];
			$data[$id]['highlight'] = $recordSet->fields['highlight'];
			$data[$id]['updated_at'] = $recordSet->fields['updated_at'];

			$data[$id]['nb_photos'] = photo::getNbPhotoFromAnnonceId($id);

			$recordSet->MoveNext();
		}
		return $data;
	}
	
	function getHighlight($limit='2')
	{
		$data = array();
		$recordSet = sql_query("SELECT * FROM annonce WHERE highlight=1 AND is_display=1 ORDER BY created_at DESC LIMIT " . $limit);
		while (!$recordSet->EOF) {
			$data[] = $recordSet->fields['id'];
			$recordSet->MoveNext();
		}
		return $data;
	}
	
	// traitement du formulaire de recherche a partir des donnees brutes ( $_POST )
	function treatForm($criteria) {
        $data = array();

        // type de transaction
        $data['type_transaction_id'] = DEFAULT_ID;
        if (isset($criteria['type_transaction_id']))
            $data['type_transaction_id'] = $criteria['type_transaction_id'];
    
        // type de bien
        $data['$type_bien_id'] = DEFAULT_ID;
        if (isset($criteria['type_bien_id']))
            $data['type_bien_id'] = $criteria['type_bien_id'];
    
        // localisation
        $data['localisation_id'] = DEFAULT_ID;
        if (isset($criteria['localisation_id']))
            $data['localisation_id'] = $criteria['localisation_id'];

        // prix minimum
        $data['prix_mini'] = 0;
        if (isset($criteria['prix_mini']) && $criteria['prix_mini']!='')
            $data['prix_mini'] = $criteria['prix_mini'];
        // prix maximum
        $data['prix_maxi'] = 999999999999;
        if (isset($criteria['prix_maxi']) && $criteria['prix_maxi']!='')
            $data['prix_maxi'] = $criteria['prix_maxi'];

		// surface minimum
		$data['surface_mini'] = 0;
		if (isset($criteria['surface_mini']) && $criteria['surface_mini']!='')
			$data['surface_mini'] = $criteria['surface_mini'];
		// surface maximum
		$data['surface_maxi'] = 999999999999;
		if (isset($criteria['surface_maxi']) && $criteria['surface_maxi']!='')
			$data['surface_maxi'] = $criteria['surface_maxi'];

		// nombre de pieces minimum
		$data['piece_mini'] = 0;
		if (isset($criteria['piece_mini']) && $criteria['piece_mini']!='')
			$data['piece_mini'] = $criteria['piece_mini'];
		// nombre de pieces maximum
		$data['piece_maxi'] = 99999;
		if (isset($criteria['piece_maxi']) && $criteria['piece_maxi']!='')
			$data['piece_maxi'] = $criteria['piece_maxi'];

		return $data;
	}
	
	function search( $type_transaction_id=DEFAULT_ID, $type_bien_id=DEFAULT_ID, $localisation_id=DEFAULT_ID, $prix_mini=false, $prix_maxi=false, $surface_mini=false, $surface_maxi=false, $piece_mini=false, $piece_maxi=false )
	{
        $sql = "SELECT id FROM annonce WHERE is_display=1 ";
        if ($type_transaction_id!=DEFAULT_ID)
            $sql.= " AND type_transaction_id=" . $type_transaction_id;
        if ($type_bien_id!=DEFAULT_ID)
            $sql.= " AND type_bien_id=" . $type_bien_id;
        if ($localisation_id!=DEFAULT_ID)
            $sql.= " AND localisation_id=" . $localisation_id;
        if ($prix_mini!==false)
            $sql.= " AND prix >= " . $prix_mini;
        if ($prix_maxi!==false)
            $sql.= " AND prix <= " . $prix_maxi;
        if ($surface_mini!==false)
            $sql.= " AND surface >= " . $surface_mini;
        if ($surface_maxi!==false)
            $sql.= " AND surface <= " . $surface_maxi;
        if ($piece_mini!==false)
            $sql.= " AND piece >= " . $piece_mini;
        if ($piece_maxi!==false)
            $sql.= " AND piece <= " . $piece_maxi;
        $sql.= " ORDER BY updated_at DESC";
		//log_error ( "DEBUG >> requete de recherche:<br/>" . $sql);

		$data = array();
		$i=0;
		$recordSet = sql_query($sql);
		while (!$recordSet->EOF) {
			++$i;
			$data[$i] = $recordSet->fields['id'];
			$recordSet->MoveNext();
		}
		return $data;
	}

	function displayMiniFiche() {
		$photo = photo::getRandom($this->photos);
		$photo = THUMB_HTTP_DIR . $photo;

		$border_color = '#3A6422';
		$text_color = '#FFFFFF';
		$bg_color = '#1B8239';
		$icon = '';
		if ($this->highlight) {
			$border_color = '#870121';
			$text_color = '#cc3300';
			$bg_color = '#D89E7D';
			$icon = getIcon('heart', 'annonce coup de coeur');
		}
	
		$html = '<div style="border: 1px solid ' . $border_color . '; margin: 0 5px; clear: both; overflow: auto; line-height: 130%;">';
		$html.= '<h4 style="color: ' . $text_color . '; background-color: ' . $bg_color . '; padding: 2px 4px;">'. $icon . $this->type_transaction->libelle . ' ' . $this->type_bien->libelle;
		$html.= ' (ref: ' . $this->reference . ')</h4>';
		//$html.= '<a href="' . URL . 'annonce/annonce.php?ref=' . $this->reference . '">';			
		$html.= '<a href="' . URL . 'annonce/annonce.php?ref=' . $this->reference . '">';			
		$html.= '<img src="' . $photo . '" alt="" style="float: left; margin: 5px;" /></a>';
		$html.= '<p style="padding: 8px 5px;">';
		$html.= 'Localisation: ' . $this->localisation->libelle;
		$html.= '<br/>' . displayPrice($this->prix);
		$html.= '<br/>' . displaySurface($this->surface);
		$html.= '<br/>'. displayPiece($this->piece);
		$html.= '<br/>Mot du conseiller: ' . $this->conseil;
		$html.= '</p>';
		$html.= '<p style="padding: 2px 5px;">' . $this->description . '</p>';
		$html.= '</div><br style="clear: both;" />';
		return $html;
    }

}
